<template>
	<view class="schedule_style">
		<LuncCalendar :showLunar="false" @dayChange="handleDayChange" @swiperChange="handleMonthChange"
			:showShrink="true" @shrinkClick="handleShrinkClick" ref="luncCalendarRef">
			<template v-slot:headerRight>
				<view style="padding-right: 50rpx;">
					<uni-icons type="list" style="margin-right: 20rpx;" @click="handleSheetList"></uni-icons>
					<uni-icons type="plusempty" @click="handlePlus" v-if="currentMode == 0"></uni-icons>
					<uni-icons type="plusempty" @click="handleAddUser" v-if="currentMode == 2"></uni-icons>
					<TkiTree idKey="value" rangeKey="text" :range="sheetList" ref="picker" @confirm="handleSheetClick"
						:multiple="false" />
					<SelectUser ref="selectUserRef" @confirm="handleSelectUserConfirm" />
				</view>
			</template>
		</LuncCalendar>
		<view class="schedule_list">
			<view style="background-color: #fff;">
				<template v-if="currentMode == 0">
					<UserGroup :type="currentMode" @success="handleUserSuccess" @handleActionType="handleActionType"
						:key="currentMode" />
				</template>
				<template v-else-if="currentMode == 1">
					<UserGroup :list="deptUsers" :type="currentMode" @success="handleUserSuccess" :key="currentMode" />
				</template>
				<template v-else-if="currentMode == 2">
					<UserGroup :list="plainOptions" @success="handleUserSuccess" @delete="handleDelFavorite"
						:type="currentMode" :key="currentMode" />
				</template>
				<template v-else-if="currentMode == 3">
					<UserGroup :list="leaders" :type="currentMode" @success="handleUserSuccess" :key="currentMode" />
				</template>
			</view>
			<view style="padding: 20rpx;">
				<uni-swipe-action>
					<uni-swipe-action-item v-for="(item, index) in list" :key="index">
						<view class="list_box" @click="handleItem(item)">
							<template v-if="currentMode == 0">
								<view class="list_box_left">
									<view>
										{{ item.start }}
									</view>
								</view>
								<view class="list_box_right">
									<view style="line-height: 1.5;">
										{{ item.title }}
									</view>
									<view
										style="color:#3485e9;margin-top: 10rpx; display: flex;justify-content: space-between;align-items: center;">
										{{ item.start }} - {{ item.end }}
										<view>
											<uni-tag :inverted="true" :text="getActionType(item.actionType)"></uni-tag>
										</view>
									</view>
								</view>
							</template>
							<template v-else>
								<view class="list_box_left" style="width: 30%;">
									<view>
										{{ item.day }}
									</view>
									<view>
										{{ item.realName }}
									</view>
								</view>
								<view class="list_box_right" style="width: 70%;">
									<view style="line-height: 1.5;">
										{{ item.title }}
									</view>
									<view
										style="color:#3485e9;margin-top: 10rpx; display: flex;justify-content: space-between;align-items: center;">
										{{ item.start }} - {{ item.end }}
										<view>
											<uni-tag :inverted="true" :text="getActionType(item.actionType)"></uni-tag>
										</view>
									</view>
								</view>
							</template>
						</view>
						<template v-slot:right>
							<view class="slot-button" v-if="currentMode == 0 && !item.closed">
								<view class="slot-button-con" style="background-color:#ff5a5f"
									@click="swipeClick({ content: { text: '删除' } }, index, item)">
									<text class="slot-button-text">删除</text>
								</view>
								<view class="slot-button-con" style="background-color:#3485e9"
									@click="swipeClick({ content: { text: '编辑' } }, index, item)">
									<text class="slot-button-text">编辑</text>
								</view>
							</view>
						</template>
					</uni-swipe-action-item>
				</uni-swipe-action>
			</view>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	onMounted
} from 'vue'
import LuncCalendar from '../component/lunc-calendar/lunc-calendar'
import UserGroup from './modules/userGroup.vue'
import SelectUser from '@/components/selectUser/index.vue'
import {
	postFormAction,
} from "@/utils/request.js";
import {
	debounce
} from '@/utils/util.js'
import {
	getTimeBetween,
	filterData,
	actionTypeList,
	dayjs
} from './useSchedule.js'
import {
	onShow,
	onLoad
} from '@dcloudio/uni-app'
import TkiTree from '@/components/tki-tree/tki-tree.vue'


const url = {
	del: '/plan/del',
	listPhase: '/plan/listPhase', //我的日程
	listPhaseByUsers: '/plan/listPhaseByUsers', // 获取多用户日程
	getDeptUsers: '/user/getDeptUsers', //获取部门人员
	listFavorite: '/user/listFavorite', //关注人员list
	createFavorite: '/user/createFavorite', //关注人员新增
	delFavorite: '/user/delFavorite', //关注人员删除
	listLeaders: '/user/listLeaders', //领导日程list
}
const list = ref([])
const sheetList = [{
	text: '我的日程',
	value: '0'
}, {
	text: '部门人员',
	value: '1'
}, {
	text: '我关注的',
	value: '2'
}, {
	text: '领导日程',
	value: '3'
}]

const currentMode = ref(0)
const queryParams = ref({
	beginDate: '',
	endDate: ''
})
const users = ref('')
const shrinkType = ref('month')
const currentType = ref('day') // day week month
const deptUsers = ref([])
const leaders = ref([])
const plainOptions = ref([])
const isRefresh = ref(false)
const allList = ref([])
const actionType = ref('0')

defineExpose({
	isRefresh,
	init
})

onLoad(() => {
	updateTitle('我的日程')
	queryParams.value.beginDate = dayjs().format("YYYY-MM-DD")
	queryParams.value.endDate = dayjs().format("YYYY-MM-DD")

	init()
	getDeptUsersData()
	getListFavoriteData()
	getListLeadersData()
})

onShow(() => {
	console.log("Schedule-onShow", isRefresh.value)
	var pages = getCurrentPages();
	// var currPage = pages[pages.length - 1]; //当前页面
	var prevPage = pages[pages.length - 1]; //上一个页面'
	console.log("prevPage", prevPage)
	if (isRefresh.value) {
		init()
		isRefresh.value = false
	}
})

function getActionType(val) {
	const record = actionTypeList.find(item => item.value == val)
	if (record) {
		return record.label
	}
	return ''
}

async function init() {
	await fetch()
	await fetchAll()
}
//类型
function handleActionType(val) {
	actionType.value = val
	init()
}
const picker = ref(null)

function handleSheetList() {
	picker.value._show()
}

function handleSheetClick(val) {
	currentMode.value = Number(val[0].value)
	if (currentMode.value == 1) {
		users.value = deptUsers.value.map(item => item.value).join(',')
	} else if (currentMode.value == 2) {
		users.value = plainOptions.value.map(item => item.value).join(',')
	} else if (currentMode.value == 3) {
		users.value = leaders.value.map(item => item.value).join(',')
	} else {
		users.value = ''
	}
	updateTitle(sheetList[currentMode.value].text)
	init()

}

function handleDayChange(e) {
	queryParams.value.beginDate = e.date
	queryParams.value.endDate = e.date
	fetch()
}
//获取当前是周还是月
function handleShrinkClick(type) {
	shrinkType.value = type
	currentType.value = type
}
const luncCalendarRef = ref(null)
//处理周和月逻辑
async function handleSetData() {
	const params = {
		beginDate: '',
		endDate: '',
	}
	if (shrinkType.value == 'week') {
		const allWeekList = luncCalendarRef.value.allWeekList
		const tranCurrent = luncCalendarRef.value.tranCurrent
		const currentWeekData = allWeekList[tranCurrent][0]
		params.beginDate = currentWeekData[0].date
		params.endDate = currentWeekData[currentWeekData.length - 1].date
	} else if (shrinkType.value == 'month') {
		const allMonthList = luncCalendarRef.value.allMonthList
		const tranIndex = luncCalendarRef.value.tranIndex
		const currentMonthData = allMonthList[tranIndex]
		params.beginDate = currentMonthData[0][0].date
		params.endDate = currentMonthData[currentMonthData.length - 1][currentMonthData[
			currentMonthData.length - 1].length - 1].date
	}
	return params
}

const fetchFun = async () => {
	list.value = await getData({
		beginDate: queryParams.value.beginDate,
		endDate: queryParams.value.endDate,
	}, 'day_list')
}

const fetch = debounce(fetchFun, 800, false)

//月change
function handleMonthChange() {
	fetchAll()
}
const fetchAllFun = async () => {
	const params = await handleSetData()
	allList.value = await getData({
		...params,
	}, 'range_list')
	let dateList = []
	console.log("allList.value", allList.value)
	allList.value.forEach(item => {
		const dates = getTimeBetween(item.myDate, item.endDate)
		dates.forEach(el => {
			dateList.push({
				date: el,
				title: ''
			})
		})
	})
	dateList = filterData(dateList)
	console.log("dateList", dateList)
	//单天查询应该查出区间内的数据
	addSign(dateList)
}
//获取当前周或者月的全部日程
const fetchAll = debounce(fetchAllFun, 800, false)

async function getData(params = {}, type = 'day_list') {
	try {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
		let _list = []
		if (currentMode.value == 0) {
			const res1 = await postFormAction(url.listPhase, {
				...params,
				actionType: actionType.value,
			});
			console.log("resres", res1)
			if (res1.data.list) {
				if (res1.data.list && res1.data.list.length > 0) {
					const list = res1.data.list;
					list.forEach((m) => {
						for (let v in m) {
							// const temp = m[v];
							if (m[v] && m[v].length) {
								m[v].forEach((item) => {
									if (type == 'day_list' || currentType.value == 'day' ||
										currentType.value == 'month') {
										_list.push({
											...item,
											title: `${item.title}`,
											start: queryParams.value.beginDate == dayjs(item.myDate).format(
												'YYYY-MM-DD') ? dayjs(item.myDate).format(
													'HH:mm') : dayjs(item.myDate).format(
														'YYYY-MM-DD HH:mm'),
											end: queryParams.value.endDate == dayjs(item.endDate).format(
												'YYYY-MM-DD') ? dayjs(item.endDate).format(
													'HH:mm') : dayjs(item.endDate).format(
														'YYYY-MM-DD HH:mm'),
										});
									} else {
										for (let n in item) {
											// const td = item[n];
											if (item[n] && item[n].length) {
												item[n].forEach((t) => {
													_list.push({
														...t,
														title: `${t.title}`,
														start: queryParams.value.beginDate == dayjs(t.myDate).format(
															'YYYY-MM-DD') ? dayjs(t.myDate).format(
																'HH:mm') : dayjs(t.myDate).format(
																	'YYYY-MM-DD HH:mm'),
														end: queryParams.value.endDate == dayjs(t.endDate).format(
															'YYYY-MM-DD') ? dayjs(t.endDate).format(
																'HH:mm') : dayjs(t.endDate).format(
																	'YYYY-MM-DD HH:mm'),
													});
												});
											}
										}
									}
								});
							}
						}
					});
				}
			}
		} else {
			if (users.value) {
				const res2 = await postFormAction(url.listPhaseByUsers, {
					...params,
					users: users.value,
					actionType: actionType.value,
					// beginDate: queryParams.value.beginDate,
					// endDate: queryParams.value.endDate,
					// actionType: isArray(c_type.value) && c_type.value.length ? c_type.value.join(',') : '',
				});
				if (res2.data && res2.data.length) {
					res2.data.forEach((it) => {
						if (it.list && it.list.length) {
							it.list.forEach((m) => {
								for (let v in m) {
									const temp = m[v];
									if (temp && temp.length) {
										temp.forEach((item) => {
											if (type == 'day_list' || currentType.value ==
												'day' || currentType.value == 'month') {
												_list.push({
													...item,
													title: `${item.title}`,
													day: dayjs(item
														.myDate)
														.format(
															'YYYY-MM-DD'
														),
													start: queryParams.value.beginDate == dayjs(item.myDate).format(
														'YYYY-MM-DD') ? dayjs(item.myDate).format(
															'HH:mm') : dayjs(item.myDate).format(
																'YYYY-MM-DD HH:mm'),
													end: queryParams.value.endDate == dayjs(item.endDate).format(
														'YYYY-MM-DD') ? dayjs(item.endDate).format(
															'HH:mm') : dayjs(item.endDate).format(
																'YYYY-MM-DD HH:mm'),
													realName: it.realName
												});
											} else {
												for (let n in item) {
													const td = item[n];
													if (td && td.length) {
														td.forEach((t) => {
															_list
																.push({
																	...
																	t,
																	title: `${t.title}`,
																	day: dayjs(
																		item
																			.myDate
																	)
																		.format(
																			'YYYY-MM-DD'
																		),
																	start: queryParams.value.beginDate == dayjs(t.myDate).format(
																		'YYYY-MM-DD') ? dayjs(t.myDate).format(
																			'HH:mm') : dayjs(t.myDate).format(
																				'YYYY-MM-DD HH:mm'),
																	end: queryParams.value.endDate == dayjs(t.endDate).format(
																		'YYYY-MM-DD') ? dayjs(t.endDate).format(
																			'HH:mm') : dayjs(t.endDate).format(
																				'YYYY-MM-DD HH:mm'),
																	resourceId: t
																		.userName,
																	realName: it
																		.realName
																});
														});
													}
												}
											}
										});
									}
								}
							});
						}
					});
				}
			}
		}
		uni.hideLoading()
		return _list
	} catch (e) {
		console.error("fetch", e)
		uni.hideLoading()
	} finally {
		uni.hideLoading()
	}
}
// 添加标记
function addSign(addList) {
	console.log("addList", addList)
	luncCalendarRef.value.clearSignList();
	// let addList = [{date: "2023-06-28",title: ""}];
	// 调用 addSignList 方法，传入需要添加的标记数组
	luncCalendarRef.value.addSignList(addList);
}
//删除
function swipeClick(e, index, item) {
	console.log("e, index, item", e, index, item)
	let {
		content
	} = e;
	if (content.text === "删除") {
		uni.showModal({
			title: "提示",
			content: "是否确定删除",
			success: (res) => {
				if (res.confirm) {
					handleDelete(item, index);
				} else if (res.cancel) {
					console.log("用户点击取消");
				}
			},
		});
	} else if (content.text === "编辑") {
		goPath({
			record: item,
			isUpdate: 1
		})
	}
}
//单个删除
function handleDelete(record, index) {
	uni.showLoading({
		title: '删除中',
		mask: true
	})
	postFormAction(url.del, {
		id: record.id,
	}).then((res) => {
		uni.showToast({
			title: res.msg,
			icon: 'none'
		});
		if (res.code == 200) {
			list.value.splice(index, 1);
		}

	}).finally(() => {
		uni.hideLoading()
	});
}

//删除关注人员
function handleDelFavorite(ids) {
	uni.showLoading({
		title: '删除中',
		mask: true
	})
	postFormAction(url.delFavorite, {
		ids
	}).then((res) => {
		uni.showToast({
			title: res.msg,
			icon: 'none'
		});
		if (res.code == 200) {
			getListFavoriteData()
		}

	}).finally(() => {
		uni.hideLoading()
	});
}
//新增
function handlePlus() {
	goPath({
		isUpdate: 0
	})
}
const selectUserRef = ref(null)
//我关注的 新增人员
function handleAddUser() {
	selectUserRef.value.open()
}
//选择用户回调
function handleSelectUserConfirm({
	selectUserList,
	label,
	value
}) {
	save(value)
}

async function save(data) {
	if (!data) {
		uni.showToast({
			title: '新增数据不能为空',
			icon: 'none',
		});
		return
	}
	try {
		let keys = ''
		const datas = data.split(',')
		const hadDatas = plainOptions.value.map(item => item.item)
		if (hadDatas && hadDatas.length > 0) {
			keys = datas.filter(val => !hadDatas.includes(val)).join(',')
		}
		if (!keys) {
			uni.showToast({
				title: '新增重复',
				icon: 'none',
			});
			return
		}
		uni.showLoading({
			title: '新增中',
			mask: true
		})
		const res = await postFormAction(url.createFavorite, {
			items: keys
		});
		getListFavoriteData();
		uni.showToast({
			title: '新增成功',
			icon: 'none',
		});
	} catch (error) {
		console.error(error);
	} finally {
		uni.hideLoading()
	}
}
//获取部门用户
async function getDeptUsersData() {
	try {
		const res = await postFormAction(url.getDeptUsers);
		const {
			data
		} = res
		deptUsers.value = data.list || [];
		deptUsers.value.forEach((item) => {
			item.label = item.realName;
			item.value = item.name;
		});
	} catch (error) {
		console.error(error);
	} finally { }
}
//获取关注人员
async function getListFavoriteData() {
	try {
		const res = await postFormAction(url.listFavorite);
		const {
			data
		} = res
		plainOptions.value = data || [];
		plainOptions.value.forEach((item) => {
			item.label = item.realName;
			item.value = item.item;
		});
	} catch (error) {
		console.error(error);
	} finally { }
}
//获取领导
async function getListLeadersData() {
	try {
		const res = await postFormAction(url.listLeaders);
		const {
			data
		} = res
		leaders.value = data || [];
		leaders.value.forEach((item) => {
			item.label = item.realName;
			item.value = item.name;
		});
	} catch (error) {
		console.error(error);
	} finally { }
}
//选择查询的用户回调
function handleUserSuccess(val) {
	users.value = val
	init()
}

//单击查看详情
function handleItem(item) {

	// goPath({
	// 	record: item,
	// 	isUpdate: 1
	// })
	goPath({
		record: item,
		isUpdate: 2
	})
}
//跳转
function goPath({
	record = {},
	isUpdate = 0
}) {
	uni.navigateTo({
		url: `/cmn/schedule/ScheduleAddOrEdit?record=${JSON.stringify(record)}&isUpdate=${isUpdate}`,
	});
}

function updateTitle(title) {
	// 微信支持
	// // 获取当前页面对象
	// const pages = getCurrentPages(); // 返回当前页面栈的信息
	// const currentPage = pages[pages.length - 1]; // 获取最后一个打开的页面

	// // 设置新的标题
	// currentPage.$page.meta.title = title;

	// 更新导航栏标题
	uni.setNavigationBarTitle({
		title,
	});
}
</script>
<style>
page {
	height: 100%;
	background-color: #f9f9f9;
}
</style>
<style lang="scss" scoped>
.schedule_style {
	height: 100%;
	display: flex;
	flex-direction: column;

	.schedule_list {
		flex: 1;
		overflow-y: auto;
		margin-top: 20rpx;

		.list_box {
			display: flex;
			justify-content: space-between;
			border-radius: 6rpx;
			padding-bottom: 40rpx;

			&_left {
				width: 20%;
			}

			&_right {
				width: 80%;
				overflow: hidden;
				background-color: #fff;
				padding: 10rpx;
				box-shadow: 10px 10px #ffffff, -10px 10px #ffffff, 10px -10px #ffffff, -10px -10px #ffffff;
			}
		}
	}
}

.slot-button {
	/* #ifndef APP-NVUE */
	display: flex;
	height: 100%;
	/* #endif */
	flex: 1;
	flex-direction: row;
	justify-content: center;
	align-items: center;
	background-color: transparent;
	padding-bottom: 20rpx;

	.slot-button-con {
		height: 100%;
		width: 100%;
		padding: 0 20rpx;
		//   border-radius: 16rpx;
		/* #ifndef APP-NVUE */
		display: flex;
		height: 100%;
		/* #endif */
		display: flex;
		// flex: 1;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		margin-right: 10rpx;
		margin-left: 10rpx;
	}

	.slot-button-text {
		color: #ffffff;
		font-size: 14px;
	}
}
</style>